import { useEffect, useState } from "react";
import "./StoFilter.scss";

interface Inputer {
  type: string;
  placeholder: string;
  key: string;
  options?: any[];
}

type StoFilterProps = {
  allData: Record<string, any>[];
  data: Record<string, any>[];
  filters: Inputer[];
  onReset: () => void;
  onSearchResult: (values: Record<string, any>[]) => void;
};

const StoFilter: React.FC<StoFilterProps> = ({
  allData,
  data,
  filters,
  onReset,
  onSearchResult,
}) => {
  /* 
  {
    name:'金',//null
    age:[18,80],//null
    gender:'二椅子'//[0,0]
  }
  */
  const [userInputs, setUserInputs] = useState<Record<string, any>>({});

  /* 组件挂载时根据用户配置的filters初始化一下 values  */
  useEffect(() => {
    console.log("ComponentDidMount");
    const obj: Record<string, any> = {};
    filters.forEach(
      ({ key, type }) => (obj[key] = type === "number" ? [0, 0] : null)
    );
    setUserInputs(obj);
  }, []);

  const renderInputer = ({ type, placeholder, options, key }: Inputer) => {
    switch (type) {
      case "text":
        return (
          <input
            onChange={(e) => {
              userInputs[key] = e.target.value;
              // setValues({ ...values });
              setUserInputs(Object.assign({}, userInputs));
            }}
            className="item"
            type={type}
            placeholder={placeholder}
          />
        );

      case "select":
        return (
          <select
            onChange={(e) => {
              console.log(key, e.target.value);

              userInputs[key] = e.target.value;
              setUserInputs(Object.assign({}, userInputs));
            }}
            className="item"
            name="sel-x"
            id=""
          >
            <option value="">{placeholder}</option>
            {options!.map((op) => (
              <option value={op}>{op}</option>
            ))}
          </select>
        );

      case "number":
        return (
          <div className="item range-box">
            <input
              onChange={(e) => {
                userInputs[key][0] = Number(e.target.value);
                setUserInputs(Object.assign({}, userInputs));
              }}
              type="number"
              defaultValue={0}
              placeholder={"最小" + placeholder}
            />
            <span>-</span>
            <input
              onChange={(e) => {
                userInputs[key][1] = Number(e.target.value);
                setUserInputs(Object.assign({}, userInputs));
              }}
              type="number"
              defaultValue={0}
              placeholder={"最大" + placeholder}
            />
          </div>
        );

      default:
        break;
    }
  };

  return (
    <>
      <div className="wrapper-sto-filter">
        {/* 字符串-模糊搜索 */}
        {/* <input className="item" type="text" placeholder="请输入用户姓名" /> */}

        {/* 枚举-下拉过滤 */}
        {/* <select className="item" name="sel-x" id="">
          <option value="">请选择性别</option>
          <option value="">A</option>
          <option value="">B</option>
          <option value="">C</option>
        </select> */}

        {/* 数值-范围过滤 */}
        {/* <div className="item range-box">
          <input type="number" placeholder="最小年龄" />
          <span>-</span>
          <input type="number" placeholder="最大年龄" />
        </div> */}

        {filters.map((inputer) => renderInputer(inputer))}

        {/* 空白 */}
        <div className="item"></div>

        {/* 搜索 + 重置 */}
        <div className="item btns">
          <button
            onClick={() => {

              // 用户的具体输入
              console.log("用户的具体输入", userInputs);


              /* 从data中按用户输入的values进行筛选，得到 filteredData 回调用户的通知函数 */
              /* {name: '桐', gender: '死变态', age: [19,90]} */


              const filteredData = allData.filter((item) => {
                /* 对每个item 逐条件审查 */
                const keys = Object.keys(userInputs);
                // console.log("keys", keys); //[name,age,gender]

                for (let i = 0; i < keys.length; i++) {
                  const k = keys[i];
                  // console.log(k, item[k], userInputs[k]);

                  const type = filters[i].type;
                  const placeholder = filters[i].placeholder;

                  if (type === "text" && (userInputs[k] === null || userInputs[k].trim() === "")) {
                    console.log("continue");
                    continue
                  }

                  if (type === "select" && (userInputs[k] === null || userInputs[k] === placeholder)) {
                    console.log("continue");
                    continue;
                  }

                  if (type === "number") {
                    let [min, max] = userInputs[k];
                    min = Number(min) || 0;
                    max = Number(max) || 0;

                    if (min === 0 && max === 0) {
                      console.log("continue");
                      continue;
                    }
                  }

                  switch (type) {
                    case "text":
                      // 姓名不含桐者fuckoff
                      if (!(item[k] as string).includes(userInputs[k])) {
                        console.log("return false");
                        return false;
                      }
                      break;

                    case "number":
                      /* 年龄不位于[19,90]区间fuckoff */
                      const num = item[k] as number;
                      const [min, max] = userInputs[k]; //age: [19,90]
                      if (num < min || num > max) {
                        console.log("return false");
                        return false;
                      }
                      break;

                    case "select":
                      /* 不是死变态的fuckoff */
                      if (item[k] !== userInputs[k]) {
                        console.log("return false");
                        return false;
                      }
                      break;

                    default:
                      break;
                  }
                }

                return true;
              });

              onSearchResult(filteredData);
            }}
          >
            搜索
          </button>
          <button onClick={onReset}>重置</button>
        </div>

        {/*  */}
      </div>
    </>
  );
};

export default StoFilter;
